<template>

  <el-dialog
    top="20px"
    :title="defaultValue.title"
    :lock-scroll="tableConfig.lockScroll"
    :append-to-body="tableConfig.appendToBody"
    :visible="tableConfig.show"
    @close="tableConfig.show = false"
    :show-close="tableConfig.close"
    :destroy-on-close="tableConfig.destroyOnClose"
    width="1100px">

    <el-form size="small" ref="formOpsSiteRef" :rules="checkRule" :model="submitData" label-width="180px">

      <el-form-item label="" prop="ico">
        <SingleImageAsyncUpload ref="userImagesRef" imageTypePath="user" objectType="4"/>
      </el-form-item>

      <el-form-item label="所属部门" prop="deptName">
        <el-input v-model.trim="searchUserParam.deptName" disabled />
      </el-form-item>

      <el-form-item label="用户名称(昵称)" prop="name">
        <el-input v-model.trim="submitData.name" />
      </el-form-item>

      <el-form-item label="登录用户名" prop="loginName">
        <el-input v-model.trim="submitData.loginName" :disabled="isEdit" />
      </el-form-item>

      <el-form-item label="密码" prop="passwordPlaintext" v-show="this.defaultValue.saveUpdSelect === 'save'" >
        <el-input v-model.trim="submitData.passwordPlaintext" show-password />
      </el-form-item>

      <el-form-item label="角色" prop="roleIdList">
        <el-select v-model="submitData.roleIdList" placeholder="请选择" clearable multiple>
          <el-option
            v-for="item in roleHaveList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-select v-model="submitData.sex" placeholder="请选择" clearable>
          <el-option
            v-for="item in sexOpt"
            :key="item.key"
            :label="item.value"
            :value="item.key">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="submitData.status" placeholder="请选择" clearable>
          <el-option
            v-for="item in statusOpt"
            :key="item.key"
            :label="item.value"
            :value="item.key">
          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="身份证" prop="idCard">
        <el-input v-model.trim="submitData.idCard" />
      </el-form-item>

      <el-form-item label="说明" prop="description">
        <el-input v-model.trim="submitData.description" type="textarea" :autosize="{minRows: 3}" />
      </el-form-item>

    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="toSaveUpd"
                 v-if="defaultValue.saveUpdSelect !== 'select'">{{ defaultValue.title }}</el-button>
      <el-button plain type="primary" @click="tableConfig.show = false">关闭</el-button>
    </span>

  </el-dialog>


</template>


<script>

import http from '@/utils/http'
import {checkNull, clearInvalid, desEncrypt} from "@/utils/utils"
import SingleImageAsyncUpload from '@/components/common/SingleImageAsyncUpload.vue';

export default {
  name: 'UserSaveUpd',
  components: {
    SingleImageAsyncUpload
  },
  data(){
    return {
      // 表格的默认值
      tableConfig: {
        // 关闭时销毁 Dialog 中的元素
        destroyOnClose: true,
        // 弹出框是否打开
        show: false,
        // 是否显示关闭按钮
        close: true,
        // 下面2个属性解决打开弹出框后没有在最上面显示的问题，导致看到的内容是一半的，需要先将滚动条移到最上面
        lockScroll: false,
        appendToBody: true,
      },
      // 默认值，进入页面后的值
      defaultValue: {
        // 弹出框标题
        title: '查看',
        // 保存还是修改or查看,取值有 select | save | upd
        saveUpdSelect: 'select'
      },
      // 提交的数据
      submitData:{
        depId: null,
        roleIdList: null,
        name: null,
        loginName: null,
        password: null,
        // 明文密码
        passwordPlaintext: null,
        sex: null,
        ico: null,
        status: null,
        description: null,
        idCard: null,
      },
      // 校验规则
      checkRule: {
        name: [{required: true, message: '请输入用户名称', trigger: 'blur'}],
        loginName: [{required: true, message: '请输入登录用户名', trigger: 'blur'}],
        passwordPlaintext: [{required: true, message: '请输入密码', trigger: 'blur'}],
        roleIdList: [{required: true, message: '请选择角色', trigger: 'change'}],
        sex: [{required: true, message: '请选择性别', trigger: 'change'}],
        status: [{required: true, message: '请选择状态', trigger: 'change'}],
      },
      // 新增的时候外部传递的查询对象
      searchUserParam:{},
      // 性别选项
      sexOpt:[
        {key: 0, value: '女性'},
        {key: 1, value: '男性'},
        {key: 9, value: '未知'},
      ],
      // 用户状态
      statusOpt:[
        {key: 1, value: '正常'},
        {key: 2, value: '停用'},
        {key: 3, value: '离职'},
      ],
      // 当前登录人拥有的角色
      roleHaveList:[],
      // 是否可编辑，true 可编辑
      isEdit: true,
    }
  },
  methods: {
    /**
     * 分页查询角色-本人拥有的
     */
    getRoleHave() {
      let query = {
        current: 1,
        size: 1000,
      }
      http.post("/role/getPage", query).then(response => {
        let res = response.data;
        if (!res.success) {
          // 401是token过期跳转的
          if (res.code !== 401) {
            this.$message.error(res.msg);
          }
          return
        }
        // 分页数据
        let data = res.data;
        // 表格数据
        this.roleHaveList = data.records

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 初始化操作
     * @param operateType 操作类型,保存还是修改or查看,取值有 select \ save \ upd
     * @param obj 如果是修改和查看，则是详细数据,需要赋值
     */
    init(operateType, obj){
      this.defaultValue.saveUpdSelect = operateType
      this.clearOldData()
      this.getRoleHave()

      if (operateType === 'save'){
        this.defaultValue.title = '新增'
        this.searchUserParam = JSON.parse(JSON.stringify(obj))
        this.submitData.status = 1
        this.submitData.sex = 9
        this.submitData.depId = obj.deptId
        this.isEdit = false

      } else if (operateType === 'upd'){
        this.defaultValue.title = '修改'
        // 要json处理下，否则会影响之前的值
        this.submitData = JSON.parse(JSON.stringify(obj))
        this.isEdit = true
        if (obj.roleList != null){
          this.submitData.roleIdList = obj.roleList.map(item => item.id)
        }
        this.searchUserParam.deptName = obj.deptName

        // 页面加载完成后执行，否则无法获取到dom
        this.$nextTick(() => {
          if (!checkNull(this.submitData.ico)){
            http.getImageUrl(this.submitData.ico).then(url => {
              this.$nextTick(() => {
                if (url) {
                  // 对图片回显进行处理，回显
                  let poster = {name: this.submitData.name, url: url, uid: this.submitData.id}
                  // 先清空，否则可能数据污染
                  this.$refs.userImagesRef.upload.fileList = []
                  this.$refs.userImagesRef.upload.fileList.push(poster)
                  this.$refs.userImagesRef.uploadHide()
                }
              })
            }).catch(e => {
              console.error('加载图片失败:', e)
            })

          }
        })

      } else {
        // 可能查看
      }

      this.tableConfig.show = true
    },
    /**
     * 清理掉旧数据
     */
    clearOldData(){
      this.submitData = {
        id: null,
        depId: null,
        roleIdList: null,
        name: null,
        loginName: null,
        passwordPlaintext: null,
        password: null,
        sex: null,
        ico: null,
        status: null,
        description: null,
        idCard: null,
      }
    },
    /**
     * 是保存还是修改
     */
    toSaveUpd(){
      if (this.defaultValue.saveUpdSelect === 'save'){
        this.saveUser()

      } else if (this.defaultValue.saveUpdSelect === 'upd'){
        this.updUser()

      } else {

      }
    },
    /**
     * 保存
     */
    saveUser(){
      // 处理加密密码
      let localStorage = window.localStorage;
      this.submitData.password = desEncrypt(this.submitData.passwordPlaintext, localStorage.loginPasswordKey);
      // 读取图片
      this.submitData.ico = this.$refs.userImagesRef.upload.fileId

      http.post("/user/saveUser", this.submitData).then(response => {
        let res = response.data;
        if (!res.success) {
          // 401是token过期跳转的
          if (res.code !== 401){
            this.$message.error(res.msg);
          }
          return
        }

        this.$message.success("保存成功");
        this.$emit('getUserPage', null)
        // 关闭弹出框,继续添加
        this.tableConfig.show = false

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 更新
     */
    updUser(){
      clearInvalid(this.submitData)
      if (!checkNull(this.$refs.userImagesRef.upload.fileId)){
        this.submitData.ico = this.$refs.userImagesRef.upload.fileId
      }
      http.post("/user/updUser", this.submitData).then(response => {
        let res = response.data;
        if (!res.success) {
          // 401是token过期跳转的
          if (res.code !== 401){
            this.$message.error(res.msg);
          }
          return
        }

        this.$message.success("更新成功");
        this.$emit('getUserPage', null)
        // 关闭弹出框
        this.tableConfig.show = false

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
  },
}

</script>

<style scoped>

</style>
